from forms import SubmitComment
from utils import *
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def comment(request, template_name):
    if not request.method == 'POST':
        raise Http404
    comment_form = SubmitComment(request.POST)
    captcha = ''
    if comment_form.is_valid():
        if comment_form.is_potential_spam(request):
            if not request.POST.get('hash'):
                captcha = Captcha()
                return render_to_response(template_name, {'request': request, 'comment_form': comment_form, 'captcha': captcha})                
            else:
                captcha = Captcha(request.POST)
                if not captcha.is_valid():
                    captcha.generate_image()
                    return render_to_response(template_name, {'request': request, 'comment_form': comment_form, 'captcha': captcha})
        instance = comment_form.save(commit=False)
        instance.author_ipaddress = request.META['REMOTE_ADDR']
        instance.save()
        return HttpResponseRedirect(comment_form.cleaned_data['next'])
    return render_to_response(template_name, {'request': request, 'comment_form': comment_form, })
